
#version 110

uniform sampler2D Tex1;
uniform sampler2D NormalMapTex;
uniform sampler2D ReflexionMap;

varying vec3 lightDir;
varying vec3 viewDir;

uniform vec3 Ka;                // Ambient reflectivity
uniform vec3 Kd;                // Diffuse reflectivity
uniform vec3 Ks;                // Specular reflectivity
uniform float Shininess;    



void main()
{
    vec3 l = lightDir;
        //l = vec3(1.0,1.0,1.0);
    float atten = max(0.0, 1.0 - dot(l, l));

    l = normalize(l);

    vec3 n = normalize(texture2D(NormalMapTex, gl_TexCoord[1].st).xyz * 2.0 - 1.0);
    vec3 v = normalize(viewDir);
    vec3 h = normalize(l + v);

    float nDotL = max(0.0, dot(n, l));
    float nDotH = max(0.0, dot(n, h));
    float power = (nDotL == 0.0) ? 0.0 : pow(nDotH, Shininess);
    
    vec4 ambient = vec4(Ka, 1.0) ;
    vec4 diffuse = vec4(Kd, 1.0) * nDotL * atten;
   vec4 specular = vec4(Ks, 1.0) * power * atten;
    //vec4 ambient = vec4(Ka, 1.0) * atten  ;
    //vec4 diffuse = vec4(Kd, 1.0) ;
   //vec4 specular = vec4(Ks, 1.0) * nDotL * power;

   float z = (gl_FragCoord.z /gl_FragCoord.w) / 1200.0;
   float fogFactor = exp2(-30.0 * z * z);
  fogFactor = clamp(fogFactor, 0.0, 1.0);

   vec4 env = texture2D( ReflexionMap, gl_TexCoord[2].st);
   vec4 color = ambient + diffuse +  specular ; 
    gl_FragColor = color * texture2D(Tex1, gl_TexCoord[0].st) + 0.25*env;
      gl_FragColor = mix(vec4(0.1,0.1,0.2,1.0), gl_FragColor, fogFactor);
}